import { Modal, notification } from 'antd';

import { usePost } from '@/api';
import { removeGraphJsonFromStorage } from '@/utils/graph';
import storage from '@/utils/storage';

interface FlowDeleteModalProps extends HTMLElementProps {
  onSuccess: () => void;
  flowId: any;
}

export interface FlowDeleteModalRef {
  open: () => void;
}

export const FlowDeleteModal = memo(
  forwardRef<FlowDeleteModalRef, FlowDeleteModalProps>((props, ref) => {
    const navigate = useNavigate();
    const [deleteVisible, setDeleteVisible] = useState(false);
    const { loading: deleteLoading, runAsync: deleteCategory } = usePost('/flow/delete', {}, { manual: true });

    const submitDelete = () => {
      deleteCategory({
        flowId: props.flowId
      }).then(() => {
        setDeleteVisible(false);
        notification.success({ message: '删除成功' });
        storage.remove('cache-flowId');
        navigate('/flow');
        removeGraphJsonFromStorage(props.flowId);
        props.onSuccess();
      });
    };

    useImperativeHandle(ref, () => ({
      open: () => {
        setDeleteVisible(true);
      }
    }));

    return (
      <>
        {props.children && (
          <div
            onClick={() => {
              setDeleteVisible(true);
            }}>
            {props.children}
          </div>
        )}
        <Modal
          title="提示"
          open={deleteVisible}
          onOk={submitDelete}
          confirmLoading={deleteLoading}
          onCancel={() => setDeleteVisible(false)}>
          <p>是否确定删除该决策流？</p>
        </Modal>
      </>
    );
  })
);
